using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Batty
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Pondhawk : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Rats rats;
        private Model ground;
        private Camera camera;

        //Will
        private Bat bat;

        private KeyboardState lastKeyboardState;

        public Camera Camera { get { return camera; } }


        public Pondhawk()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            rats = new Rats(this);
            

            //Will
            bat = new Bat(this);

            camera = new Camera(graphics);
            camera.UseChaseCamera = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            camera.Initialize();
            camera.Eye = new Vector3(10, 10, 10);

            lastKeyboardState = Keyboard.GetState();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            rats.LoadContent(Content);
            ground = Content.Load<Model>("GrassField2");

            //Will
            bat.LoadContent(Content);
         
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            camera.Update(gameTime);

            // TODO: Add your update logic here
            rats.Update(gameTime);

            int i=rats.rats.Count();;
            System.Diagnostics.Trace.WriteLine("Rats Count:" +i.ToString());
            for(int j=i; i>0;i--)
            {
                rats.testRatsForCollision(rats.rats.Last());
                rats.rats.RemoveLast();
            }
          //  System.Diagnostics.Trace.WriteLine("Rats Count:" + rats.ratsCopy.Count().ToString());
            for(int j=rats.ratsCopy.Count(); j>0;j--)
            {
                rats.rats.AddLast(rats.ratsCopy.Last());
                rats.ratsCopy.RemoveLast();
            }
           
            rats.ratsCopy.Clear();
           // rats.finishCollision();


            //Will
            KeyboardState keyboardState = Keyboard.GetState();

            if ((keyboardState.IsKeyDown(Keys.X) && lastKeyboardState.IsKeyUp(Keys.X)))
            {
                bat.Flapping = !bat.Flapping;
            }
            lastKeyboardState = keyboardState;

            if ((keyboardState.IsKeyDown(Keys.Space) && lastKeyboardState.IsKeyUp(Keys.X)))
            {
                
            }


            if (keyboardState.IsKeyDown(Keys.E))
            {
                bat.Flap = 1;
                bat.Flapping = true;
            }
            else
            {
                bat.Flap = 0;
                bat.Flapping = false;
            }

            if (keyboardState.IsKeyDown(Keys.Left))
            {
                bat.TurnRate = 1f;
                bat.BankRate = -.5f;

            }
            else if (keyboardState.IsKeyDown(Keys.Right))
            {
                bat.TurnRate = -1f;
                bat.BankRate = .5f;

            }
            else
            {
                bat.TurnRate = 0;
                bat.BankRate = 0;
            }

            if (keyboardState.IsKeyDown(Keys.Up))
            {
                bat.ElevRate = 1;
            }
            else if (keyboardState.IsKeyDown(Keys.Down))
            {
                bat.ElevRate = -1;
            }
            else
            {
                bat.ElevRate = 0;
            }


            Matrix[] transforms = new Matrix[bat.Model.Bones.Count];
            bat.Model.CopyAbsoluteBoneTransformsTo(transforms);
            Matrix batTransform = bat.Transform;

            foreach (ModelMesh mesh in bat.Model.Meshes)
            {
                BoundingSphere bs = mesh.BoundingSphere;
                bs = bs.Transform(transforms[mesh.ParentBone.Index] * batTransform);
                if (false)
                {

                    this.Initialize();

                }
            }

            bat.Update(gameTime);

            camera.UseChaseCamera = true;
            camera.DesiredEye = Vector3.Transform(new Vector3(0, 100, -50), bat.Transform);
            camera.Center = bat.Position;
            camera.Up = bat.Transform.Up;



            

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Blue);

            // TODO: Add your drawing code here
            rats.Draw(graphics, gameTime, this);
            DrawModel(ground, Matrix.Identity);

            //Will
            bat.Draw(graphics, gameTime);

            base.Draw(gameTime);
        }


        private void DrawModel(Model model, Matrix world)
        {
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] * world;
                    effect.View = Camera.View;
                    effect.Projection = Camera.Projection;
                }
                mesh.Draw();
            }
        }
    }
}
